/**
 * Essay控制器
 * 处理作文相关的HTTP请求
 */

import * as essayService from '../services/essayService.js';

/**
 * 清洗作文内容 - 移除系统调试信息
 * @param {string} content - 原始内容
 * @returns {string} 清洗后的内容
 */
function sanitizeContent(content) {
  if (!content || typeof content !== 'string') return content;
  
  let cleaned = content;
  
  // 移除JSON格式的调试信息
  cleaned = cleaned.replace(/\{[^}]*"status"[^}]*"tool_used"[^}]*"message"[^}]*\}/g, '');
  cleaned = cleaned.replace(/\{[^}]*"current_step"[^}]*"next_step"[^}]*\}/g, '');
  cleaned = cleaned.replace(/\{[^}]*"random_string"[^}]*\}/g, '');
  
  // 移除MCP相关标识
  cleaned = cleaned.replace(/mcp-feedback-enhanced/g, '');
  cleaned = cleaned.replace(/mcp-[a-z-]+/gi, '');
  
  // 移除多余的空白行
  cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
  
  return cleaned.trim();
}

/**
 * 创建作文
 * POST /api/v1/essays
 */
export const createEssay = async (req, res, next) => {
  try {
    const { title, content, gradeLevel } = req.body;
    const userId = req.user.id; // 从认证中间件获取用户ID

    // 清洗内容，移除系统调试信息
    const cleanedContent = sanitizeContent(content);

    const result = await essayService.createEssay(userId, title, cleanedContent, gradeLevel);

    res.status(201).json(result);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取作文详情
 * GET /api/v1/essays/:essayId
 */
export const getEssayById = async (req, res, next) => {
  try {
    const { essayId } = req.params;

    const result = await essayService.getEssayById(essayId);

    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户作文列表
 * GET /api/v1/essays/user/:userId
 */
export const getUserEssays = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const { limit, offset, gradeLevel, status } = req.query;

    // 构建筛选条件
    const filters = {};
    if (limit !== undefined) filters.limit = limit;
    if (offset !== undefined) filters.offset = offset;
    if (gradeLevel) filters.gradeLevel = gradeLevel;
    if (status) filters.status = status;

    const result = await essayService.getUserEssays(userId, filters);

    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

/**
 * 更新作文
 * PUT /api/v1/essays/:essayId
 */
export const updateEssay = async (req, res, next) => {
  try {
    const { essayId } = req.params;
    const userId = req.user.id; // 从认证中间件获取用户ID
    const updates = req.body;

    // 如果更新内容包含content字段，清洗它
    if (updates.content) {
      updates.content = sanitizeContent(updates.content);
    }

    const result = await essayService.updateEssay(essayId, userId, updates);

    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

/**
 * 删除作文
 * DELETE /api/v1/essays/:essayId
 */
export const deleteEssay = async (req, res, next) => {
  try {
    const { essayId } = req.params;
    const userId = req.user.id; // 从认证中间件获取用户ID

    const result = await essayService.deleteEssay(essayId, userId);

    res.status(200).json(result);
  } catch (error) {
    next(error);
  }
};

